package com.x.crm.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.x.crm.http.response.login.CrmAccount;
import com.x.erp.model.User;
import com.x.erp.rpc.UserRpcService;

import com.x.framework.controller.ResultCode;
import com.x.framework.controller.ResultModel;
import com.x.security.model.Resource;
import com.x.security.model.SecurityAccount;
import com.x.security.rpc.SecurityRpcService;
import com.x.security.util.Constant;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

@RestController
public class UserController {
	private static ModelAndView loginModelAndView = new ModelAndView(Constant.redirect + "/index.jsp");

	private static final Logger logger = LogManager.getLogger(UserController.class);
	@Reference
	private SecurityRpcService securityRpcService;
	@Reference
	private UserRpcService userRpcService;

	@RequestMapping("/getUserSession")
	public ModelAndView login(HttpServletRequest request) {

		HttpSession session = request.getSession();
		SecurityAccount account = (SecurityAccount) session.getAttribute(Constant.SECURITY_ACCOUNT);
		List<Resource> accountResourceList = account.getResourceList();
//        account.setResourceUrlList(this.getResourceUrlList(accountResourceList));
		account.setResourceList(this.getResourceList(accountResourceList));

		User user = new User();
		user.setAccountId(account.getAccountId());
		List<User> loginUsers = userRpcService.selectUserList(user);
		if (loginUsers.size() > 0) {
			User loginUser = loginUsers.get(0);
			session.setAttribute(SessionKey.loginUser, loginUser);
//            Boolean isCharge = false;
//            Integer userType = loginUser.getUserType();
//            if (userType == 40 || userType == 22){
//                isCharge = true;
//            }
			CrmAccount crmAccount = new CrmAccount(account);
//            crmAccount.setIsCharge(isCharge);
			session.setAttribute("crmAccount", JSON.toJSONString(crmAccount));
			session.setAttribute(SessionKey.account, crmAccount);
			session.setAttribute("marketId", loginUser.getMarketId());
			session.setAttribute("userId", loginUser.getUserId());
			session.setAttribute("userName", loginUser.getUserName());
			session.setAttribute("userMobile", loginUser.getUserMobile());
		}
		return loginModelAndView;
	}

	@RequestMapping(value = "/LoginJson", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel loginJson(HttpServletRequest request) {
		HttpSession session = request.getSession();
		Object obj = session.getAttribute(Constant.SECURITY_ACCOUNT);
		if (obj == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, Constant.securityAccountErrorMessage);
		}
		SecurityAccount securityAccount = (SecurityAccount) obj;

		User user = new User();
		user.setAccountId(securityAccount.getAccountId());
		List<User> userList = userRpcService.selectUserList(user);
		if (userList.size() == 0) {
			return new ResultModel(ResultCode.RESULT_FAIL, Constant.securityAccountErrorMessage);
		} else {
			user = userList.get(0);
		}
//		if (user.getShopId() == null ){
//			return new ResultModel(ResultCode.RESULT_FAIL, Constant.securitySessionNotMessage);
//		}
		HashMap<String,Object> crmUserInfo = new HashMap<>();
		crmUserInfo.put("resourceList",securityAccount.getResourceList());
		crmUserInfo.put("roleList",securityAccount.getRoleList());
		crmUserInfo.put("userId",user.getUserId());
		crmUserInfo.put("userName",user.getUserName());
		crmUserInfo.put("userMobile",user.getUserMobile());
		crmUserInfo.put("marketId",user.getMarketId());
		if (user.getMarket() != null) {
			crmUserInfo.put("marketName",securityAccount.getAccountId());
		}
		crmUserInfo.put("shopId",user.getShopId());
		if (user.getShop() != null) {
			crmUserInfo.put("shopName", user.getShop().getShopName());
		}
		session.removeAttribute(Constant.SECURITY_ACCOUNT);
		return new ResultModel(ResultCode.RESULT_SUCCESS, null, crmUserInfo);
	}


	private List<Resource> getResourceList(List<Resource> resourceList) {
		List<Resource> menus = new ArrayList();
		Iterator var3 = resourceList.iterator();

		while (var3.hasNext()) {
			Resource menu = (Resource) var3.next();
			if (menu.getResourceParentId().equals("1")) {
				menus.add(menu);
			}
		}

		List<Resource> list = new ArrayList();
		Iterator var7 = menus.iterator();

		while (var7.hasNext()) {
			Resource menu = (Resource) var7.next();
			menu = this.getResourceList(menu, resourceList);
			list.add(menu);
		}

		return list;
	}

	private List<String> getResourceUrlList(List<Resource> resourceList) {
		List<String> resourceUrlList = new ArrayList();
		Iterator var3 = resourceList.iterator();

		while (var3.hasNext()) {
			Resource resource = (Resource) var3.next();
			if (resource.getResourceUrl() != null) {
				resourceUrlList.add(resource.getResourceUrl());
			}
		}

		return resourceUrlList;
	}

	private Resource getResourceList(Resource menu, List<Resource> menuItems) {
		Iterator var3 = menuItems.iterator();

		while (var3.hasNext()) {
			Resource menuItem = (Resource) var3.next();
			if (menu.getResourceId().equals(menuItem.getResourceParentId())) {
				menuItem = this.getResourceList(menuItem, menuItems);
				menu.getResourceList().add(menuItem);
			}
		}

		return menu;
	}

	private String getClientIp(HttpServletRequest request) {
		String remoteAddr = request.getHeader("X-Forwarded-For");
		if (this.isEffective(remoteAddr) && remoteAddr.indexOf(",") > -1) {
			String[] array = remoteAddr.split(",");
			String[] var4 = array;
			int var5 = array.length;

			for (int var6 = 0; var6 < var5; ++var6) {
				String element = var4[var6];
				if (this.isEffective(element)) {
					remoteAddr = element;
					break;
				}
			}
		}

		if (!this.isEffective(remoteAddr)) {
			remoteAddr = request.getHeader("X-Real-IP");
		}

		if (!this.isEffective(remoteAddr)) {
			remoteAddr = request.getRemoteAddr();
		}

		return remoteAddr;
	}

	private boolean isEffective(String remoteAddr) {
		boolean isEffective = false;
		if (null != remoteAddr && !"".equals(remoteAddr.trim()) && !"unknown".equalsIgnoreCase(remoteAddr.trim())) {
			isEffective = true;
		}

		return isEffective;
	}
}
